package com.sky.module.system.heart.manager;

import com.sky.module.system.heart.handle.HeartBeatRecordHandler;
import com.sky.module.system.heart.runnable.HeartRunnable;
import com.sun.corba.se.spi.orbutil.threadpool.WorkQueue;
import org.jetbrains.annotations.NotNull;

import java.util.concurrent.*;

/**
 * @author
 * @date 2023/3/11 15:32
 **/
public class HeartBeatManager {

    private ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;

    private HeartBeatRecordHandler heartBeatRecordHandler;

    public HeartBeatManager(HeartBeatRecordHandler heartBeatRecordHandler) {
        this.heartBeatRecordHandler = heartBeatRecordHandler;

        scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1, r -> {
            final Thread thread = new Thread(r);
            if (!thread.isDaemon()) {
                thread.setDaemon(true);
            }
            return thread;
        });
        // 开始心跳检测
        this.beignHeart();
    }

    /***
     * @description 开始心跳
     *
     * @return void
     * @date 2023/3/11 16:10
     *
     */
    private void beignHeart() {
        //  首次延迟执行延迟时间     延迟的时间   时间单位是毫秒
        // HeartRunnable 任务对象，里面有对心跳的一些初始化信息，然后run 重复收集执行
        scheduledThreadPoolExecutor.
                scheduleWithFixedDelay(new HeartRunnable(heartBeatRecordHandler),
                        // 延迟2秒  每次10秒
//                        2, 10, TimeUnit.SECONDS);
                        // 延迟6秒，每1分钟检测心跳
                        60 * 1000L, 1000L * 60, TimeUnit.MILLISECONDS);
    }


}
